<template>
  <div class="feeds-container">
    <div v-if="loading && page === 1" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="list.length === 0" class="empty-container">
      <el-empty description="暂无收藏" />
    </div>
    
    <div v-else 
      v-infinite-scroll="loadMore" 
      :infinite-scroll-disabled="loading || !hasMore"
      :infinite-scroll-distance="10"
      class="infinite-scroll-container">
      <Waterfall :list="list" :width="220" :hasAroundGutter="false" style="max-width: 1260px">
        <template #item="{ item }">
          <div class="card" @click="openArticleDetail(item.articleID)">
            <LazyImg 
              :url="item.imageUrl || getDefaultImageUrl()" 
              style="border-radius: 8px" 
            />
            <div class="footer">
              <a class="title"><span>{{ item.title }}</span></a>
              <div class="author-wrapper">
                <a class="author" @click.stop="goToUserProfile(item.authorID)">
                  <img class="author-avatar" :src="item.authorAvatar || defaultAvatar" />
                  <span class="name">{{ item.authorName || '未知用户' }}</span>
                </a>
                <span 
                  class="like-wrapper" 
                  :class="{ 'like-active': item.isFavorited }"
                  @click.stop="toggleFavorite(item)"
                >
                  <el-icon><Star /></el-icon>
                  <span class="count">{{ item.favoriteCount || 0 }}</span>
                </span>
              </div>
            </div>
          </div>
        </template>
      </Waterfall>
      
      <div v-if="loading" class="loading-more">
        <el-loading />
      </div>
      
      <div v-if="!hasMore && list.length > 0" class="no-more">
        没有更多内容了
      </div>
    </div>
    
    <!-- 文章详情模态窗口 -->
    <div v-if="showArticleDetail" class="article-modal-overlay" @click.self="closeArticleDetail">
      <ArticleDetail 
        :article-id="currentArticleId" 
        @close="closeArticleDetail"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Star, Search } from "@element-plus/icons-vue";
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next";
import "vue-waterfall-plugin-next/dist/style.css";
import { ref, onMounted, computed } from "vue";
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';
import { FavoriteRecordApi } from '@/api/FavoriteRecordApi.js';
import { ElMessage } from 'element-plus';
import UserUtil from "@/utils/User/User.js";
import ArticleDetail from '@/components/ArticleDetail.vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 文章列表
const list = ref([]);
const loading = ref(false);
const hasMore = ref(true);

// 分页参数
const page = ref(1);
const pageSize = ref(10);
const userId = ref(null);

// 文章详情模态窗口状态
const showArticleDetail = ref(false);
const currentArticleId = ref(null);

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';

// 作者信息缓存
const authorCache = ref({});

// 收藏状态缓存 - 存储收藏ID而不仅是布尔值
const favoriteCache = ref({});

// 打开文章详情
const openArticleDetail = (articleId) => {
  currentArticleId.value = articleId;
  showArticleDetail.value = true;
  // 禁止背景滚动
  document.body.style.overflow = 'hidden';
};

// 关闭文章详情
const closeArticleDetail = () => {
  showArticleDetail.value = false;
  // 恢复背景滚动
  document.body.style.overflow = '';
};

// 跳转到用户个人页面
const goToUserProfile = (userId) => {
  if (!userId) return;
  router.push({
    path: '/otherUser',
    query: { userId }
  });
};

// 获取作者信息
const fetchAuthorInfo = async (authorId) => {
  // 如果缓存中已有该作者信息，直接返回
  if (authorCache.value[authorId]) {
    console.log(`从缓存获取作者信息, 作者ID: ${authorId}`, authorCache.value[authorId]);
    return authorCache.value[authorId];
  }
  
  try {
    // 调用API获取作者信息
    console.log(`获取作者信息, 作者ID: ${authorId}`);
    const authorInfo = await UserProfileApi.getUserInfo(authorId);
    console.log(`作者信息获取结果:`, authorInfo);
    
    // 缓存作者信息
    authorCache.value[authorId] = authorInfo;
    
    return authorInfo;
  } catch (error) {
    console.error(`获取作者信息失败, 作者ID: ${authorId}`, error);
    return {
      username: '未知用户',
      headshot: defaultAvatar
    };
  }
};

// 检查用户是否已收藏文章
const checkFavoriteStatus = async (articleId) => {
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 获取当前用户ID
  const currentUserId = UserUtil.getUserId();
  if (!currentUserId) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 生成缓存键
  const cacheKey = `${currentUserId}-${articleId}`;
  
  // 如果缓存中已有该收藏状态，直接返回
  if (favoriteCache.value[cacheKey] !== undefined) {
    console.log(`从缓存获取收藏状态, 文章ID: ${articleId}`, favoriteCache.value[cacheKey]);
    return favoriteCache.value[cacheKey];
  }
  
  try {
    // 调用API检查收藏状态
    const response = await TravelNoteApi.getFavoriteId(currentUserId, articleId);
    console.log(`API获取收藏状态原始响应, 文章ID: ${articleId}`, response);
    
    // 解析JSON字符串响应
    let result;
    try {
      // 如果响应已经是对象，则不需要解析
      if (typeof response === 'object') {
        result = response;
      } else {
        result = JSON.parse(response);
      }
      console.log(`解析后的收藏状态, 文章ID: ${articleId}`, result);
    } catch (parseError) {
      console.error(`解析收藏状态JSON失败:`, parseError);
      return { isFavorited: false, favoriteId: null };
    }
    
    // 缓存收藏状态和ID
    const favoriteInfo = {
      isFavorited: result.status === "success",
      favoriteId: result.status === "success" ? result.favoriteID : null
    };
    
    favoriteCache.value[cacheKey] = favoriteInfo;
    console.log(`缓存收藏信息, 键: ${cacheKey}`, favoriteInfo);
    
    return favoriteInfo;
  } catch (error) {
    console.error(`获取收藏状态失败, 文章ID: ${articleId}`, error);
    return { isFavorited: false, favoriteId: null };
  }
};

// 切换收藏状态
const toggleFavorite = async (article) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    const currentUserId = UserUtil.getUserId();
    const articleId = article.articleID;
    const cacheKey = `${currentUserId}-${articleId}`;
    
    if (article.isFavorited) {
      // 已收藏，需要取消收藏
      // 尝试从缓存获取收藏ID
      let favoriteId = favoriteCache.value[cacheKey]?.favoriteId;
      
      if (!favoriteId) {
        // 如果缓存中没有收藏ID，则从API获取
        console.log(`缓存中没有收藏ID，从API获取, 用户ID: ${currentUserId}, 文章ID: ${articleId}`);
        const response = await TravelNoteApi.getFavoriteId(currentUserId, articleId);
        console.log('获取收藏ID原始响应:', response);
        
        // 解析JSON字符串响应
        let favoriteResult;
        try {
          // 如果响应已经是对象，则不需要解析
          if (typeof response === 'object') {
            favoriteResult = response;
          } else {
            favoriteResult = JSON.parse(response);
          }
          console.log('解析后的收藏ID结果:', favoriteResult);
        } catch (parseError) {
          console.error('解析收藏ID JSON失败:', parseError);
          ElMessage.error('获取收藏ID失败');
          return;
        }
        
        if (favoriteResult.status === 'success') {
          favoriteId = favoriteResult.favoriteID;
        } else {
          ElMessage.error('获取收藏ID失败');
          return;
        }
      }
      
      if (favoriteId) {
        // 使用收藏ID删除收藏记录
        console.log(`准备删除收藏, ID: ${favoriteId}`);
        const deleteResult = await TravelNoteApi.deleteCollection(favoriteId);
        console.log('删除收藏结果:', deleteResult);
        
        // 更新UI
        article.isFavorited = false;
        if (article.favoriteCount > 0) {
          article.favoriteCount--;
        }
        
        // 更新缓存
        favoriteCache.value[cacheKey] = { isFavorited: false, favoriteId: null };
        console.log(`更新缓存, 键: ${cacheKey}`, favoriteCache.value[cacheKey]);
        
        ElMessage.success('取消收藏成功');
        
        // 从列表中移除该文章
        list.value = list.value.filter(item => item.articleID !== article.articleID);
      } else {
        ElMessage.error('收藏ID不存在，无法取消收藏');
      }
    } else {
      // 未收藏，需要添加收藏
      console.log(`准备添加收藏, 文章ID: ${articleId}`);
      const createResult = await TravelNoteApi.collectTravelNote(articleId);
      console.log('添加收藏结果:', createResult);
      
      // 从创建结果中获取收藏ID
      let newFavoriteId = null;
      if (createResult && createResult.favoriteID) {
        newFavoriteId = createResult.favoriteID;
      }
      
      // 更新UI
      article.isFavorited = true;
      article.favoriteCount = (article.favoriteCount || 0) + 1;
      
      // 更新缓存
      favoriteCache.value[cacheKey] = { isFavorited: true, favoriteId: newFavoriteId };
      console.log(`更新缓存, 键: ${cacheKey}`, favoriteCache.value[cacheKey]);
      
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error);
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 获取当前登录用户ID
onMounted(async () => {
  try {
    // 使用 UserUtil 判断用户是否登录
    if (UserUtil.isLogin()) {
      userId.value = UserUtil.getUserId();
      await fetchFavorites();
    } else {
      ElMessage.warning('请先登录');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
});

// 获取收藏文章列表
const fetchFavorites = async () => {
  if (loading.value || !hasMore.value) return;
  
  loading.value = true;
  try {
    console.log(`获取用户 ${userId.value} 的收藏文章`);
    const favoriteRecords = await FavoriteRecordApi.getFavoriteRecordsByUserId(userId.value);
    
    console.log('API返回的原始收藏数据:', favoriteRecords);
    
    if (Array.isArray(favoriteRecords) && favoriteRecords.length > 0) {
      // 计算当前页的收藏记录
      const startIndex = (page.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      const currentPageFavorites = favoriteRecords.slice(startIndex, endIndex);
      
      if (currentPageFavorites.length === 0) {
        hasMore.value = false;
      } else {
        // 处理每篇收藏的游记，获取文章详情、图片、作者信息
        const articlesWithDetails = await Promise.all(
          currentPageFavorites.map(async (favorite) => {
            try {
              console.log(`处理收藏文章: ${favorite.contentID}`);
              
              // 获取文章详情
              const articleDetail = await TravelNoteApi.browseTravelNote(favorite.contentID);
              console.log(`文章 ${favorite.contentID} 详情:`, articleDetail);
              
              // 并行获取图片和作者信息
              const [imageData, authorInfo] = await Promise.all([
                TravelNoteApi.getFirstImage(favorite.contentID),
                fetchAuthorInfo(articleDetail.authorID)
              ]);
              
              // 构建完整的文章对象
              return {
                ...articleDetail,
                articleID: favorite.contentID,
                favoriteID: favorite.favoriteID,
                imageUrl: (imageData && imageData.imageUrl) ? imageData.imageUrl : getDefaultImageUrl(),
                authorName: authorInfo.username,
                authorAvatar: authorInfo.headshot,
                isFavorited: true, // 收藏列表中的文章默认已收藏
                favoriteId: favorite.favoriteID,
                favoriteCount: articleDetail.favoriteCount || 0
              };
            } catch (error) {
              console.error(`处理收藏文章 ${favorite.contentID} 详情失败:`, error);
              return null;
            }
          })
        );
        
        // 过滤掉获取失败的文章
        const validArticles = articlesWithDetails.filter(article => article !== null);
        
        // 将新数据添加到列表中
        list.value = [...list.value, ...validArticles];
        console.log('处理后的收藏文章列表:', list.value);
        
        page.value++;
        
        // 如果当前页获取的文章数量小于页大小，说明没有更多数据了
        if (currentPageFavorites.length < pageSize.value) {
          hasMore.value = false;
        }
      }
    } else {
      hasMore.value = false;
      if (page.value === 1) {
        ElMessage.info('暂无收藏文章');
      } else {
        ElMessage.info('没有更多收藏文章了');
      }
    }
  } catch (error) {
    console.error('获取收藏文章列表失败:', error);
    ElMessage.error('获取收藏文章列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    fetchFavorites();
  }
};

// 获取默认图片URL
const getDefaultImageUrl = () => {
  return `https://ts1.tc.mm.bing.net/th/id/R-C.738148bdb2da83e7bab5d7f63d1190cd?rik=usj6CNEFf1B92w&riu=http%3a%2f%2fpic.baike.soso.com%2fp%2f20140311%2f20140311162033-282564199.jpg&ehk=eRgO3fxJa6CqLG1pjx7VaCyEV5qGOTFOR9r3yG1veYA%3d&risl=&pid=ImgRaw&r=0`;
};
</script>

<style lang="less" scoped>
.feeds-container {
  position: relative;
  transition: width 0.5s;
  margin: 0 auto;
  
  .loading-container, .empty-container {
    padding: 20px;
    text-align: center;
  }
  
  .infinite-scroll-container {
    min-height: 100px;
  }
  
  .loading-more {
    text-align: center;
    padding: 20px 0;
  }
  
  .no-more {
    text-align: center;
    color: #999;
    padding: 20px 0;
    font-size: 14px;
  }

  .footer {
    padding: 12px;
    .title {
      margin-bottom: 8px;
      word-break: break-all;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      font-weight: 500;
      font-size: 14px;
      line-height: 140%;
      color: #333;
    }

    .author-wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 20px;
      color: rgba(51, 51, 51, 0.8);
      font-size: 12px;
      transition: color 1s;

      .author {
        display: flex;
        align-items: center;
        color: inherit;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 12px;

        .author-avatar {
          margin-right: 6px;
          width: 20px;
          height: 20px;
          border-radius: 20px;
          border: 1px solid rgba(0, 0, 0, 0.08);
          flex-shrink: 0;
        }

        .name {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .like-wrapper {
        position: relative;
        cursor: pointer;
        display: flex;
        align-items: center;

        .count {
          margin-left: 2px;
        }
      }
      
      .like-active {
        color: #ff2442;
      }
    }
  }
  
  .card {
    cursor: pointer;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-5px);
    }
  }
}

// 添加模态窗口样式
.article-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5); // 半透明黑色背景
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}
</style>
